package com.d3works.studio.web;

import com.d3works.i18n.I18n;
import com.d3works.inject.Beans;
import com.d3works.meta.schema.actions.ActionView;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import com.d3works.studio.db.WsAuthenticator;
import com.d3works.studio.db.repo.WsAuthenticatorRepository;
import com.d3works.studio.service.ws.WsAuthenticatorService;
import com.google.inject.Inject;

public class WsAuthenticatorController {

  @Inject protected WsAuthenticatorService wsAuthenticatorService;

  public void authenticate(ActionRequest request, ActionResponse response) {

    WsAuthenticator wsAuthenticator = request.getContext().asType(WsAuthenticator.class);

    if (wsAuthenticator.getId() == null) {
      return;
    }

    wsAuthenticator = Beans.get(WsAuthenticatorRepository.class).find(wsAuthenticator.getId());

    if (wsAuthenticator.getAuthTypeSelect().equals("basic")) {
      wsAuthenticatorService.authenticate(wsAuthenticator);
      response.setReload(true);
    } else {
      response.setView(
          ActionView.define(I18n.get("Authenticate"))
              .add("html", wsAuthenticatorService.generatAuthUrl(wsAuthenticator))
              .param("target", "_blank")
              .map());
    }
  }
}
